package com.changgou.web.filter;

import com.changgou.web.service.AuthService;
import com.changgou.web.service.AuthServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
 * @author Sherlock
 * @date 2020/3/16
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    public  static final String LOGIN_URL="http://localhost:8001/api/oauth/toLogin";

    @Autowired
    private AuthService authService;



    /**
     * 1）判断当前请求是否为登录请求，是的话，则放行
     * 2) 判断cookie中是否存在信息, 没有的话，拒绝访问,跳转到登录界面
     * 3）判断redis中令牌是否存在，没有的话，拒绝访问,跳转到登录界面
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //1）判断当前请求是否为登录请求，是的话，则放行
        String path = request.getURI().getPath();
        if (path.contains("/api/oauth/login")||!URLFilter.hasAuthorize(path)){
            return chain.filter(exchange);
        }
        //2) 判断cookie中是否存在信息, 没有的话，拒绝访问
        String jti = authService.getJtiFromCookie(request);
        if (StringUtils.isEmpty(jti)){
            //cookie中没有Jti(未登录),跳转到登录界面
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
            return this.toLoginPage(LOGIN_URL+"?from="+path,exchange);
        }
        //3）判断redis中令牌是否存在，没有的话，拒绝访问
        String token = authService.getTokenFromRedis(jti);
        if (StringUtils.isEmpty(token)){
            //redis中没有这个token(登录过期),跳转到登录界面
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
            return this.toLoginPage(LOGIN_URL+"?from="+path,exchange);
        }
        //给需要验证的请求加上token请求头
        request.mutate().header("Authorization","Bearer "+token);
        return chain.filter(exchange);
    }


    /**
     * 跳转登录页面
     * @param loginUrl
     * @param exchange
     * @return
     */
    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
